package com.user.service.impl;


import com.common.exception.users.UsersException;
import com.user.domain.pojo.Permission;
import com.user.domain.pojo.Role;
import com.user.domain.pojo.User;
import com.user.mapper.UserMapper;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 自定义实现 UserDetailsService 实现构建用户主体信息
 */
public class UserDetailsServiceImpl  implements UserDetailsService {

    @Resource
    UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.querySelectByUsername(username);
        if (user == null){
            throw new UsersException(UsersException.USER_NULL);
        }
        if (user.getStatus() != 1){
            throw new UsersException("该账号已被禁用");
        }
        // 得到权限列表
        List<GrantedAuthority> grantedAuthority = getGrantedAuthority(username);
        return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(),grantedAuthority);
    }

    /**
     * 根据用户名 返回权限列表
     * @param username 用户名
     * @return 权限列表
     */
    public List<GrantedAuthority> getGrantedAuthority(String username){
        // 得到角色列表
        List<Role> roles = userMapper.querySelectRoleByUsername(username);
        // 得到权限列表
        List<Permission> permissions = userMapper.querySelectPermissionByUsername(username);
        // 拼接为Security需要的GrantedAuthority
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>(roles.size() + permissions.size());
        for (Role role : roles) {
            grantedAuthorities.add(new SimpleGrantedAuthority(role.getName()));
        }
        for (Permission permission : permissions) {
            grantedAuthorities.add(new SimpleGrantedAuthority(permission.getName()));
        }
        return grantedAuthorities;
    }
}
